﻿// Smiley class, (c)2010 Knihovnik
// This file is licensed under LGPL license, see more at http://www.gnu.org/licenses/lgpl.html
namespace FacebookChat
{

	#region Usings

	using System;
	using System.Diagnostics;
	using System.Drawing;
	using System.Drawing.Imaging;
	using System.IO;
	using Smileys = FacebookChat.Emoticons.Properties;

	#endregion 

	/// <summary>
	/// Class that represents smiley
	/// </summary>
	internal sealed class Smiley : IDisposable
	{

		#region Members

		private string[] m_assoc; // Asociations
		private Image m_image; // Image
		private string m_name; // Name of smiley from Resources

		private static string _temp;

		#endregion

		#region Constructor

		/// <summary>
		/// Static constructor
		/// </summary>
		static Smiley()
		{
			_temp = Path.GetTempPath();
		}

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="name">Smiley name</param>
		/// <param name="assoc">List of associations</param>
		public Smiley(string name, string[] assoc)
		{
			this.m_assoc = assoc;
			this.m_name = name;
			this.m_image = Smileys.Resources.ResourceManager.GetObject(name) as Image;
		}

		#endregion

		#region Properties

		/// <summary>
		/// Gets smiley image path (from temp directory)
		/// </summary>
		public string ImgSrc
		{
			get
			{
				return Path.Combine(_temp, string.Format("{0}.png", this.m_name.GetHashCode()));
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// Replaces smiley from message with html img tag
		/// </summary>
		/// <param name="message">Original message</param>
		/// <returns>Changed message</returns>
		public string Replace(string message)
		{
			foreach(string assoc in this.m_assoc)
				while (message.Contains(assoc))
					message = message.Replace(assoc, string.Format("<img src=\"{0}\" />", this.ImgSrc));
			return message;

		}

		/// <summary>
		/// Extracts smiley image to temp directory
		/// </summary>
		public void Extract()
		{
			if(this.m_image == null)
				return;
			try
			{
				this.m_image.Save(this.ImgSrc, ImageFormat.Png);
			}
			catch (Exception ex)
			{
				Debug.Write(ex);
			}
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			if (File.Exists(this.ImgSrc))
				File.Delete(this.ImgSrc);
		}

		#endregion

	}
}
